﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.Common;
using PMS.EntityQuery;
using PMS.EntityManage;
using System.Data.SqlClient;

public partial class Modules_Flow_FlowStepAdd : System.Web.UI.Page
{
    IPerf_FlowHandler flowHandler = new Perf_FlowManage();

    IPerf_Flow_StepsHandler flowStepHandler = new Perf_Flow_StepsManage();

    ISys_RoleHandler roleHandler = new Sys_RoleManage();
    ISys_PostHandler postHandler = new Sys_PostManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!(Request["ID"] != null && Request["ID"] != string.Empty))
        {
            if (!CheckPurviews())
            {
                Response.Redirect("~/Login.aspx");
            }
        }
        if (!IsPostBack)
        {
            FillDDl();
            if (ddlAppWay.SelectedValue != string.Empty)
            {
                FillProcessMode(int.Parse(ddlAppWay.SelectedValue));
            }
            dataBind();
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("401021"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    private void CheckUpdatePurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("401022"))
            {
                txtName.ReadOnly = false;
                ddlAppWay.Enabled = true;
                ddlMode.Enabled = true;
                txtRemark.ReadOnly = false;
                btnSave.Enabled = true;

            }
            else
            {
                txtName.ReadOnly = true;
                ddlAppWay.Enabled = false;
                ddlMode.Enabled = false;
                txtRemark.ReadOnly = true;
                btnSave.Enabled = false;

            }
        }
        else
        {
            txtName.ReadOnly = true;
            ddlAppWay.Enabled = false;
            ddlMode.Enabled = false;
            txtRemark.ReadOnly = true;
            btnSave.Enabled = false;
        }
    }

    private void FillDDl()
    {
        ////上一步骤

        //if (Request["FlowID"] != null)
        //{
        //    DataTable dtPre = flowStepHandler.GetPerf_Flow_StepsList("IsEnable=@IsEnable and Flow_ID=@FlowID", new SqlParameter[] { new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")), new SqlParameter("@FlowID", Request["FlowID"]) }, " Step_Num asc");

        //    ddlPreStep.DataSource = dtPre;
        //    ddlPreStep.DataTextField = "StepName";
        //    ddlPreStep.DataValueField = "ID";
        //    ddlPreStep.DataBind();
        //    ddlPreStep.Items.Insert(0, new ListItem(string.Empty, "0"));

        //    //下一步骤
        //    DataTable dtNext = flowStepHandler.GetPerf_Flow_StepsList("IsEnable=@IsEnable and Flow_ID=@FlowID", new SqlParameter[] { new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")), new SqlParameter("@FlowID", Request["FlowID"]) }, " Step_Num asc");

        //    ddlNextStep.DataSource = dtNext;
        //    ddlNextStep.DataTextField = "StepName";
        //    ddlNextStep.DataValueField = "ID";
        //    ddlNextStep.DataBind();
        //    ddlNextStep.Items.Insert(0, new ListItem(string.Empty, "0"));

        //}

    }

    private void FillProcessMode(int way)
    {
        ddlMode.Items.Clear();
        ddlMode.Enabled = true;

        DataTable dtMode = new DataTable();

        if (way.ToString().Equals(Enums.ApproveWay.Role.ToString("d")))//角色
        {
            dtMode = roleHandler.GetSys_RoleList("Status=@Status", new SqlParameter[] { new SqlParameter("@Status", Enums.NormalStatus.Vallid.ToString("d")) });

        }
        else if (way.ToString().Equals(Enums.ApproveWay.DepartMent.ToString("d")))//部门
        {
            dtMode = orgHandler.GetSys_OrganizationList("Status=@Status", new SqlParameter[] { new SqlParameter("@Status", Enums.NormalStatus.Vallid.ToString("d")) });

        }

        else if (way.ToString().Equals(Enums.ApproveWay.Personal.ToString("d")))//个人
        {
            dtMode = userHandler.GetSys_UserList("Status=@Status", new SqlParameter[] { new SqlParameter("@Status", Enums.NormalStatus.Vallid.ToString("d")) });

        }

        ddlMode.DataSource = dtMode;
        ddlMode.DataTextField = "Name";
        ddlMode.DataValueField = "ID";
        ddlMode.DataBind();
        ddlMode.Items.Add(new ListItem("请选择...", "0"));
        ddlMode.SelectedIndex = dtMode.Rows.Count;
    }

    protected void ddlAppWay_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (ddlAppWay.SelectedValue != "0")
        //{           
        FillProcessMode(int.Parse(ddlAppWay.SelectedValue));
        //}
        //else
        //{
        //    ddlMode.Items.Clear();
        //    ddlMode.Enabled = false;
        //}
    }

    private bool CheckIsFirstStep()
    {
        bool istrue = true;
        if (Request["FlowID"] != null)
        {
            DataTable dt = flowStepHandler.GetPerf_Flow_StepsList("Flow_ID=@FlowID and IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@FlowID", Request["FlowID"]), new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")) });
            if (dt != null && dt.Rows.Count > 0)
            {
                istrue = false;
            }
        }
        return istrue;
    }

    private int GetLastStepID()
    {
        int stepID = 0;
        if (Request["FlowID"] != null)
        {
            DataTable dt = flowStepHandler.GetPerf_Flow_StepsList("Flow_ID=@FlowID and IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@FlowID", Request["FlowID"]), new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")) }, " ID desc");
            if (dt != null && dt.Rows.Count > 0)
            {
                stepID = int.Parse(dt.Rows[0]["ID"].ToString());
            }
        }
        return stepID;
    }

    private int GetLastNum()
    {
        int num = 0;
        if (Request["FlowID"] != null)
        {
            DataTable dt = flowStepHandler.GetPerf_Flow_StepsList("Flow_ID=@FlowID and IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@FlowID", Request["FlowID"]), new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")) }, "  ID desc");
            if (dt != null && dt.Rows.Count > 0)
            {
                num = int.Parse(dt.Rows[0]["Step_Num"].ToString());
            }
        }
        return num;
    }

    private bool IsExistNameUpdate(string name, int id)
    {
        bool istrue = false;
        DataTable dt = flowStepHandler.GetPerf_Flow_StepsList("IsEnable=@IsEnable and StepName=@StepName and ID!=@ID", new SqlParameter[] { new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")), new SqlParameter("@StepName", name), new SqlParameter("@ID", id.ToString()) });
        if (dt != null && dt.Rows.Count > 0)
        {
            istrue = true;
        }
        return istrue;
    }

    public bool IsExistName(string name)
    {
        bool istrue = false;
        DataTable dt = flowStepHandler.GetPerf_Flow_StepsList("IsEnable=@IsEnable and StepName=@StepName ", new SqlParameter[] { new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")), new SqlParameter("@StepName", name) });
        if (dt != null && dt.Rows.Count > 0)
        {
            istrue = true;
        }
        return istrue;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Perf_Flow_StepsQuery query = new Perf_Flow_StepsQuery();

        //更新
        if (Request["StepID"] != null)
        {
            query = flowStepHandler.GetPerf_Flow_StepsQuery(int.Parse(Request["StepID"]));

            if (query != null)
            {
                if (IsExistNameUpdate(txtName.Text.Trim(), query.ID))
                {
                    Jscript.Alert("流程步骤名称已经存在,请重新输入!", this.Page);
                    return;
                }
            }
        }
        else
        {
            if (IsExistName(txtName.Text.Trim()))
            {
                Jscript.Alert("流程步骤名称已经存在,请重新输入!", this.Page);
                return;
            }

            if (!CheckIsFirstStep())
            {
                query.Prev_ID = GetLastStepID();
                query.Step_Num = GetLastNum() + 1;
            }
            else
            {
                query.Step_Num = 1;
            }

            query.IsEnable = int.Parse(Enums.NormalStatus.Vallid.ToString("d"));
            query.Flow_ID = int.Parse(Request["FlowID"]);
        }

        query.StepName = txtName.Text.Trim();
        query.Remark = txtRemark.Text.Trim();
        query.Approve_Way = int.Parse(ddlAppWay.SelectedValue);
        if (ddlAppWay.SelectedValue == Enums.ApproveWay.Role.ToString("d"))
        {
            query.Role_ID = int.Parse(ddlMode.SelectedValue);
            query.Org_ID = 0;
            query.User_ID = 0;
        }
        else if (ddlAppWay.SelectedValue == Enums.ApproveWay.DepartMent.ToString("d"))
        {
            query.Org_ID = int.Parse(ddlMode.SelectedValue);
            query.Role_ID = 0;
            query.User_ID = 0;
        }
        else if (ddlAppWay.SelectedValue == Enums.ApproveWay.Personal.ToString("d"))
        {
            query.User_ID = int.Parse(ddlMode.SelectedValue);
            query.Org_ID = 0;
            query.Role_ID = 0;
        }

        //更新
        if (Request["StepID"] != null)
        {
            if (flowStepHandler.UpdatePerf_Flow_Steps(query))
            {
                Jscript.Alert("操作成功!", this.Page);
                Jscript.ReturnAndClose(this.Page, "true");
            }
        }
        else
        {
            if (!CheckIsFirstStep())
            {
                int id = 0;
                int lastID = GetLastStepID();
                if (flowStepHandler.InsertPerf_Flow_Steps(query, ref id))
                {
                    Perf_Flow_StepsQuery lQuery = flowStepHandler.GetPerf_Flow_StepsQuery(lastID);
                    if (lQuery != null)
                    {
                        lQuery.Next_ID = id;
                        flowStepHandler.UpdatePerf_Flow_Steps(lQuery);
                        Jscript.Alert("操作成功!", this.Page);
                        Jscript.ReturnAndClose(this.Page, "true");
                    }
                }
            }
            else
            {
                if (flowStepHandler.InsertPerf_Flow_Steps(query))
                {
                    Jscript.Alert("操作成功!", this.Page);
                    Jscript.ReturnAndClose(this.Page, "true");
                }
                else
                {
                    Jscript.Alert("操作失败!", this.Page);
                }
            }
        }

    }

    private void dataBind()
    {
        //初妈化步骤信息
        if (Request["StepID"] != null && Request["StepID"] != string.Empty)
        {
            Perf_Flow_StepsQuery query = flowStepHandler.GetPerf_Flow_StepsQuery(int.Parse(Request["StepID"]));
            if (query != null)
            {
                txtName.Text = query.StepName;

                //ddlPreStep.SelectedValue = query.Prev_ID.ToString();
                //ddlNextStep.SelectedValue = query.Next_ID.ToString();
                ddlAppWay.SelectedValue = query.Approve_Way.ToString();
                FillProcessMode(int.Parse(ddlAppWay.SelectedValue.ToString()));
                ddlMode.SelectedValue = query.Approve_Way.ToString() == Enums.ApproveWay.Role.ToString("d") ? query.Role_ID.ToString() : query.Approve_Way.ToString() == Enums.ApproveWay.DepartMent.ToString("d") ? query.Org_ID.ToString() : query.User_ID.ToString();
                txtRemark.Text = query.Remark;
            }
        }
    }
}
